'use strict';
const fs = require('fs');
const path = require('path');
var COS = require('cos-nodejs-sdk-v5');
//故名思意 异步二进制 写入流
const awaitWriteStream = require('await-stream-ready').write;
//管道读入一个虫洞。
const sendToWormhole = require('stream-wormhole');
const dayjs = require('dayjs');
const Service = require('egg').Service;

class UploadService extends Service {
    async uploadStrom(stream) {
        // const stream = await this.ctx.getFileStream();
        console.log('-----------获取数据 start--------------');
        console.log(stream.fields);
        console.log('-----------获取数据 end--------------');
        // 基础的目录
        const uplaodBasePath = 'app/public/uploads';
        // 生成文件名
        const filename = `${Date.now()}${Number.parseInt(
          Math.random() * 1000,
        )}${path.extname(stream.filename).toLocaleLowerCase()}`;
        // 生成文件夹
        const dirname = dayjs(Date.now()).format('YYYY/MM/DD');

        function mkdirsSync(dirname) {
            if (fs.existsSync(dirname)) {
                return true;
            } else {
                if (mkdirsSync(path.dirname(dirname))) {
                    fs.mkdirSync(dirname);
                    return true;
                }
            }
        }
        mkdirsSync(path.join(uplaodBasePath, dirname));
        // 生成写入路径
        const target = path.join(uplaodBasePath, dirname, filename);
        // 写入流
        const writeStream = fs.createWriteStream(target);
        try {
            //异步把文件流 写入
            await awaitWriteStream(stream.pipe(writeStream));
        } catch (err) {
            //如果出现错误，关闭管道
            await sendToWormhole(stream);
            this.ctx.body = "错误"
            return null
                //   this.error();
        }
        return { url: path.join('/public/uploads', dirname, filename) }
        // this.success({ url: path.join('/public/uploads', dirname, filename) });
    }
    async uploadCos(stream,hot) {

        var cos = new COS({
            SecretId: 'AKIDUs4Qdc3w9IDGIBoDPM5DLGvYw4xZrrev',
            SecretKey: 'Byg8KK7fz457zblocBUo32lW1HI3XFo6'
        });

        // 生成文件名
        const filename = `${Date.now()}${Number.parseInt(
            Math.random() * 1000,
          )}${hot || path.extname(stream.filename).toLocaleLowerCase()}`;
        // 生成文件夹
        const dirname = dayjs(Date.now()).format('YYYY-MM-DD');

        let result = await new Promise((reslove, reject) => {
            cos.putObject({
                Bucket: 'img-1259163267',
                /* 必须 */
                Region: 'ap-nanjing',
                /* 必须 */
                Key: dirname + "/" + filename,
                /* 必须 */
                StorageClass: 'STANDARD',
                Body: stream, // 上传文件对象
                onProgress: function(progressData) {
                    console.log(JSON.stringify(progressData));
                }
            }, function(err, data) {
                if (!err) {
                    reslove(data)
                } else {
                    reject(err)
                }
                console.log(err || data);
            });
        })

        return result
    }
}

module.exports = UploadService;